package com.exam.action;


import java.security.NoSuchAlgorithmException;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.exam.bean.User;
import com.exam.service.UserService;
import com.exam.service.impl.UserServiceImpl;
import com.exam.util.IpUtil; 
import com.exam.util.MD5Util;
 
import com.exam.util.Page;
import com.exam.util.PageResult;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 2012-12-03 用户的Action类
 * 
 * @author MuLing
 * 
 */
public class UserAction extends ActionSupport {

	private User user = new User();
	private List<User> userList = new ArrayList<User>();
	private Page page = new Page();

	// 添加用户信息
	public String add() {
		UserService service = new UserServiceImpl();
		HttpServletRequest request = ServletActionContext.getRequest();
 
		String md5_pw;
		try {
			md5_pw = MD5Util.getMD5(user.getPassword()); // md5加密
			user.setPassword(md5_pw);
			try {
				if ("1".equals(request.getParameter("sex"))) {
					user.setSex(true);
				} else {
					user.setSex(false);
				}

				user.setIp(IpUtil.getIpAddr(request));
				user.setCreateDateTime(new Date());
				user.setStatus(true);// true表示该用户可用
				service.add(user);

				return listForPageService(service, "");
			} catch (Exception e) {
				addActionError("注册用户时出异常" + e.getMessage());
				return "exception";
			}
		} catch (NoSuchAlgorithmException e1) {
			addActionError("注册用户时出异常" + e1.getMessage()); 
			return "exception";
		}
	}

	// 删除用户信息
	public String delete() {
		UserService service = new UserServiceImpl();
		try {
			String idStr = ServletActionContext.getRequest().getParameter("id");
			if (idStr != null && !"".equals(idStr)) {
				service.delete(Integer.parseInt(idStr));
			}
		} catch (Exception e) {
			addActionError("删除出异常" + e.getMessage());
			return "exception";
		}
		return listForPageService(service, "");
	}

	// 批量删除信息
	public String deleteList() {
		UserService service = new UserServiceImpl();

		HttpServletRequest request = ServletActionContext.getRequest();// 取得Request对象
		String[] checkIDs = request.getParameterValues("checkIDs");// 取得页面上需要删除的信息对应的ID
		List<Integer> idList = new ArrayList<Integer>();// 用于存储需要删除的信息对应的ID的集合
		if (checkIDs != null && checkIDs.length > 0) {
			for (String strID : checkIDs) {
				idList.add(Integer.parseInt(strID));// 将ID保存到List集合中
			}
		}

		try {
			service.delete(idList);// 执行删除操作
		} catch (Exception e) {
			addActionError("批量删除出异常" + e.getMessage());
			return "exception";
		}
		return listForPageService(service, "");
	}

	// 编辑用户之前进行查询
	public String edit() {
		UserService service = new UserServiceImpl();
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String idStr = request.getParameter("id");
			if (idStr != null && !"".equals(idStr)) {
				user = service.findModel(Integer.parseInt(idStr));// 查询操作
			}
		} catch (Exception e) {
			addActionError("查询出异常" + e.getMessage());
			return "exception";
		}
		return "editUser";
	}

	// 更新用户信息
	public String update() {
		UserService service = new UserServiceImpl(); 
		String md5_pw;

		try {
			md5_pw = MD5Util.getMD5(user.getPassword());
			user.setPassword(md5_pw);
			try {
				service.update(user);// 更新操作
			} catch (Exception e) {
				addActionError("更新出异常" + e.getMessage());
				return "exception";
			}

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			addActionError("更新出异常" + e.getMessage());
			return "exception";
		}// md5加密
 
		try {
			service.update(user);// 更新操作
		} catch (Exception e) {
			addActionError("更新出异常" + e.getMessage());
			return "exception";
		} 
		return listForPageService(service, "");
	}

	//更新个人信息
	public String updatePeronalInfo() {
		UserService service = new UserServiceImpl();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		User sessionUser = (User) session.getAttribute("loginuser"); 
		String md5_pw;
		try {
			md5_pw = MD5Util.getMD5(sessionUser.getPassword());
			user.setPassword(md5_pw);
			try {
				service.update(user);// 更新操作
			} catch (Exception e) {
				addActionError("更新出异常" + e.getMessage());
				return "exception";
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			addActionError("更新出异常" + e.getMessage());
			return "exception";
		}// md5加密 
		user.setPassword(sessionUser.getPassword());
		try {
			service.update(user);// 更新操作
		} catch (Exception e) {
			addActionError("更新出异常" + e.getMessage());
			return "exception";
		} 
		return listForPageService(service, "");
	}

	// 根据ID查看详细信息
	public String find() {
		UserService service = new UserServiceImpl();
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String idStr = request.getParameter("id");
			if (idStr != null && !"".equals(idStr)) {
				user = service.findModel(Integer.parseInt(idStr));
			}
		} catch (Exception e) {
			addActionError("查询出异常" + e.getMessage());
			return "exception";
		}
		return "findUser";
	}

	// 列出所有的信息
	public String list() {
		UserService service = new UserServiceImpl();
		try {
			userList = service.findList("");
		} catch (Exception e) {
			addActionError("查询出异常" + e.getMessage());
			return "exception";
		}
		return "listUsers";
	}

	// 没有添加查询的分页
	public String listByPage() {
		UserService service = new UserServiceImpl();
		return listForPageService(service, "");// 调用为分页服务的方法
	}

	// 有条件的分页
	public String listByWherePage() {
		UserService service = new UserServiceImpl();
		HttpServletRequest request = ServletActionContext.getRequest();

		StringBuilder strWhere = new StringBuilder();
		String userID = user.getUserID();
		Integer identity = user.getIdentity(); 
		String sexStr =  request.getParameter("sex");  
 
		strWhere.append("u_userID like ").append("'%").append(userID != null ? userID : "").append("%' ");
 
		if (identity != null && identity != -1) {
			strWhere.append(" and u_identity=").append(identity);
		}

		if ("1".equals(sexStr)) {
			strWhere.append(" and u_sex=").append(true);
		} else if ("0".equals(sexStr)) {
			strWhere.append(" and u_sex=").append(false);
		}

		return listForPageService(service, strWhere.toString());// 调用为分页服务的方法
	}

	@SuppressWarnings("unchecked")
	// 为分页处理服务的方法
	public String listForPageService(UserService service, String strWhere) {
		PageResult pageResult = null;
		try {
			if (strWhere != null && !"".equals(strWhere)) {
				pageResult = service.findListByPage(strWhere, page);// 按条件查询
			} else {
				pageResult = service.findListByPage(page);// 简单分页
			}
			userList = pageResult.getList();// 获得记录
			page = pageResult.getPage();// 获得分页信息

		} catch (Exception e) {
			addActionError("查询出异常" + e.getMessage());
			return "exception";
		}
		return "listUsers";
	}

	/**
	 * 管理员登录入口方法
	 * 
	 * @return
	 */
	public String login_Admin() {
		String strWhere = "u_userID='" + user.getUserID()
				+ "' AND u_identity = " + 0;
		String loginErrorStr = "login_Admin";
		String okStr = "login_AdminOK";
		return loginMethod(strWhere, loginErrorStr, okStr);// 调用登录方法
	}

	/**
	 * 普通用户登录方法入口
	 * 
	 * @return
	 */
	public String login() {
		String strWhere = "u_userID='" + user.getUserID()
				+ "' AND u_identity = " + 1;
		String loginErrorStr = "login";
		String okStr = "loginOK";
		return loginMethod(strWhere, loginErrorStr, okStr);// 调用登录方法
	}

	/**
	 * 为登录提供的公共方法
	 * 
	 * @param strWhere
	 * @return
	 */
	private String loginMethod(String strWhere, String loginErrorStr,
			String loginOk) {

		String returnStr = "exception";

		UserService service = new UserServiceImpl();
		HttpServletRequest request = ServletActionContext.getRequest();
		String code = request.getParameter("checkcode");

		String randomCode = (String) ActionContext.getContext().getSession()
				.get("randomCode");

		if (code != null && code.equalsIgnoreCase(randomCode)) {
			try {
				List<User> list = service.findList(strWhere);
				if (list != null && list.size() > 0) { 
					User loginUser = list.get(0);// 根据用户名查看用户信息保存到loginUser
					if (loginUser != null) {
						String md5_pw = MD5Util.getMD5(user.getPassword());// 对用户输入的密码进行加密
						if (md5_pw != null
								&& md5_pw.equals(loginUser.getPassword())) {// 对加密后的密码进行匹配
 
							user = loginUser;
							loginUser.setLastLoginDateTime(new Date());// 创建登录时间
							loginUser.setIp(IpUtil.getIpAddr(request));// 记录登录ip
							service.update(loginUser);// 更新数据

							returnStr = loginOk; // 匹配成功
						} else {// 匹配失败
							addActionError("用户名或密码不正确！");
							returnStr = loginErrorStr;
						}
					} else {
						addActionError("系统中似乎不存在该用户！");
						returnStr = loginErrorStr;
					}
				} else {
					addActionError("系统中似乎不存在该用户！");
					returnStr = loginErrorStr;
				}

			} catch (Exception e) {
				addActionError("登录出异常" + e.getMessage());
				returnStr = "exception";
			}
		} else {
			addActionError("输入的验证码不正确！");
			returnStr = loginErrorStr;
		}
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.containsKey("user")) {
			session.remove("user");// 如果现在存在先去除掉
		}
		session.put("loginuser", user);// 用户放到session中
		return returnStr;
	} 
	/**
	 * 注册普通用户
	 * 
	 * @return
	 */
	public String register() {
		UserService service = new UserServiceImpl();
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			user.setIp(IpUtil.getIpAddr(request));
			if ("1".equals(request.getParameter("sex"))) {
				user.setSex(true);
			} else {
				user.setSex(false);
			}
			user.setCreateDateTime(new Date());

			user.setIdentity(1);// 1表示普通用户
			user.setStatus(true);// true表示该用户可用
 
			String md5_pw;
			try {
				md5_pw = MD5Util.getMD5(user.getPassword()); // md5加密
				user.setPassword(md5_pw);
				service.add(user);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				addActionError("更新出异常" + e.getMessage());
				return "exception";
			}// md5加密 

			return "registerOK";
		} catch (Exception e) {
			addActionError("登录出异常" + e.getMessage());
			return "exception";
		}
	}

	public static void main(String[] args) {
		UserService service = new UserServiceImpl();
		try {
			System.out.println(service.findModel(34));
		} catch (Exception e) {
		}
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param userList
	 *            the userList to set
	 */
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	/**
	 * @return the userList
	 */
	public List<User> getUserList() {
		return userList;
	}

	/**
	 * @param page
	 *            the page to set
	 */
	public void setPage(Page page) {
		this.page = page;
	}

	/**
	 * @return the page
	 */
	public Page getPage() {
		return page;
	}

	private static final long serialVersionUID = 1L;

}
